package com.travel.service;

import io.jsonwebtoken.Jwts;
import org.apache.hc.client5.http.utils.Base64;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:Jasenon_ce
 * Date: 2025.04.28/下午10:16
 */
public class WeatherUtil {

    private static final String private_key_pem = """
                                            -----BEGIN PRIVATE KEY-----
                                            MC4CAQAwBQYDK2VwBCIEIPPlv1UICcdPmA9ch3fCZ/uR1mT70e1es0vBjcAI4kFz
                                            -----END PRIVATE KEY-----
                                            """;
    private static final String project_id = "288AGQX64N";
    private static final String credential_id = "T45F5A75X9";

    public static String createToken() throws NoSuchAlgorithmException, InvalidKeySpecException {
        String pem = private_key_pem.replace("-----BEGIN PRIVATE KEY-----","")
                .replaceAll(System.lineSeparator(),"")
                .replaceAll("\n","")
                .replace("-----END PRIVATE KEY-----","");
        byte[] encoded = Base64.decodeBase64(pem.getBytes(StandardCharsets.UTF_8));
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory keyFactory = KeyFactory.getInstance("EdDSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        long now = System.currentTimeMillis() / 1000;
        Map<String, Object> payload = new HashMap<>();
        payload.put("iat", now - 30);
        payload.put("exp", now + 900);
        payload.put("sub", project_id);

        Map<String, Object> headers = new HashMap<>();
        headers.put("kid", credential_id);
        headers.put("alg", "EdDSA");

        // 生成JWT(等效Python的jwt.encode)
        return Jwts.builder()
                .header().add(headers).and()
                .claims(payload)
                .signWith(privateKey, Jwts.SIG.EdDSA) // 显式指定EdDSA算法
                .compact();
    }

}
